package thread;

public class ThreadPrint extends Thread {
    private String threadName;
    private static final Object lock = new Object();
    private static int i = 0;
    private static final int MAX_COUNT = 5;

    /**
     * 不同线程交替打印
     * @param name
     */
    public ThreadPrint(String name) {
        threadName = name;
        System.out.println("creating: " + threadName);
    }

    @Override
    public void run() {
        synchronized (lock) {
            while (i < MAX_COUNT) {
                while (!threadName.equals("Thread-1") && i % 2 == 0) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                while (!threadName.equals("Thread-2") && i % 2 != 0) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("Thread -> " + threadName + " is running; --> " + i);
                i++;

                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        ThreadPrint t1 = new ThreadPrint("Thread-1");
        ThreadPrint t2 = new ThreadPrint("Thread-2");

        t1.start();
        t2.start();
    }
}
